define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        statsModelCls = require('js/apps/stats/models'),
        uploader = require('js/utils/uploader'),
        app = Backbone.history;
    require('magnific');

        var ShowListView = Backbone.View.extend({
            tagName: "div",
            events: {
                'click #search': 'doSearch',
            },

            initialize: function (options) {
                this.options = options;
                this.collection = new models.ShowCollection();
                this.collection.bind('change reset remove', this.renderWithData, this);
            },
            render: function () {
                this.$el.html("");
                $(window).scrollTop(0);
                return this;
            },
            doSearch: function () {
                var options = utils.getAllInput("#sidebar_right", true),
                    searched = utils.getAllInput('#sidebar_right');
                utils.saveSearched('op/show', searched);
                app.navigate(utils.composeQueryString('#op/show/', options), {
                    trigger: true
                });
            },
            renderWithData: function () {
                this.$el.html(this.template({
                    items: this.collection.toJSON(),
                    searched: utils.getSearched('op/show'),
                }));
                var that = this;
                utils.renderTable('main-list', {
                    $orderby: that.options.$orderby || 'id',
                    sortCallback: function (field) {
                        that.options.$orderby = field;
                        that.options.$page = 1;
                        var newUrl = utils.composeQueryString('#op/show/', that.options);
                        app.navigate(newUrl, {
                            trigger: true
                        });
                    }
                });
                utils.getPaginator(that.options, this.collection.total, '#op/show/');

                return this;
            },
            load: function () {
                this.collection.fetch({
                    reset: true,
                    data: this.options,
                    error: function (c, r, o) {
                        notify.notifyResp(r);
                        $('#content').append('<h4 class="text-muted">无数据</h4>');
                    },
                });
            }
        });
        exports.List = Backbone.View.extend({
            el: "#content_wrapper",
            template: "op/ShowList.html",
            initialize: function (options) {
                this.options = options;
            },
            render: function () {
                var view = new ShowListView(this.options);
                view.template = this.template;

                this.$el.empty();
                this.$el.append(view.render().el);
                view.load();

                return this;
            }
        });
        var ShowDetailView = Backbone.View.extend({
            tagName: "div",
            className: "panel-body pn",
            events: {
                'click #showSave': 'toSave',
                'click .delete-image': 'deleteImage',
            },
            initialize: function (options) {
                this.model = new models.Show();
                this.deletedImages = [];
                if (options.id) {
                    this.model.set('id', options.id);
                } else {
                    this.model.set(options.params);
                    this.account = new statsModelCls.Account();
                    this.account.set('id', options.params.user_id);
                    delete options.params;
                    this.account.bind('change reset', this.renderWithData, this);
                }
                this.model.bind('change reset', this.renderWithData, this);
            },
            render: function () {
                this.$el.html("");
                $(window).scrollTop(0);
                return this;
            },
            deleteImage: function (e) {
                e.preventDefault();
                var url = $(e.currentTarget).next('a').attr('href');
                $(e.currentTarget).parents('div.thumb').remove();

                this.deletedImages.push(url);
                return false;
            },
            _getCurrentInputs: function () {
                var data = {};
                if (this.model.get('status') <= 2) {
                    data.content = $('#inputContent').val();
                    data.images = [];
                    $('.detail-image').each(function () {
                        data.images.push($(this).attr('src'));
                    });
                    data.images = data.images.join(',');
                }
                if (this.model.get('status') >= 2) {
                    data.status = parseInt($('#inputStatus').val());
                    data.verify_comment = $('#inputComment').val();
                    if (data.status == 4 || data.status == 16) {
                        data.verify_award = parseInt($('#inputVerifyAward').val()) || 0;
                    } else {
                        data.verify_comment = $('#inputComment').val();
                    }
                    if ($('#inputHighlight').is(':checked')) {
                        data.highlight = 1;
                    } else {
                        data.highlight = 0;
                    }
                }
                return data;
            },
            toSave: function (e) {
                e.preventDefault();
                var data = this._getCurrentInputs();
                if (data.status == 2 && data.verify_comment == '') {
                    notify.error('错误', '拒绝应说明原因');
                    return;
                }
                var postData = {
                    success: function (model, response) {
                        notify.success('提示', '保存成功！');
                        setTimeout(function () {
                            history.back();
                        }, 500);
                    },
                    error: function (model, response) {
                        notify.notifyResp(response);
                    }
                };
                if (data.status) {
                    // create new show
                    postData.patch = true;
                    postData.activity_id = this.activity_id;
                }
                this.model.save(data, postData);
                if (this.deletedImages.length > 0)
                    $.post('admin/image/delete/', {
                        urls: this.deletedImages.join(',')
                    }).done(function() {
                        this.deletedImages = [];
                    });
                return false;
            },
            renderWithData: function () {
                this.$el.html(this.template({
                    info: this.model.toJSON(),
                    account: this.account ? this.account.toJSON() : {},
                }));
                $('.image-popup').magnificPopup({
                    type: 'image',
                    closeOnContentClick: true,
                    mainClass: 'mfp-img-mobile',
                    image: {
                        verticalFit: true,
                        titleSrc: function (item) {
                            return '<a href="' + item.el.attr('href') +
                                '" target="_blank">查看原图</a>';
                        }
                    }
                });
                var that = this;
                uploader.getSingleUploader('uploadImg', function (url) {
                    that.model.set(that._getCurrentInputs());
                    var images = (that.model.get('images') || '').split(',');
                    images.push(url);
                    that.model.set('images', images.join(','));
                }, true);
                uploader.getSingleUploader('uploadAvatar', function (url) {
                    $.post('/admin/virtual/account/' + that.model.get('user_id'),
                        JSON.stringify({ avatar_id: url })).fail(function (d) {
                        notify.notifyResp(d);
                        }).then(function () {
                            that.account.set('avatar_id', url);
                    })
                });
                return this;
            },
            load: function () {
                if (this.model.get('id')) {
                    this.model.fetch({
                        reset: true
                    });
                } else {
                    this.account.fetch({ reset: true });
                }
            }
        });
        exports.Detail = Backbone.View.extend({
            el: "#content_wrapper",
            template: "op/ShowDetail.html",
            initialize: function (options) {
                this.options = options;
            },
            render: function () {
                var view = new ShowDetailView(this.options);
                view.template = this.template;

                this.$el.empty();
                this.$el.append(view.render().el);
                view.load();

                return this;
            }
        });

});